package com.itheima.filter;



import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckerFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("filter过滤前");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //1.获取请求url地址
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;
        String url=httpServletRequest.getRequestURI().toString();

        //2.解析url中是否含有login关键字，有则放行
        if (url.contains("login")){
            log.info("登录页面放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.获取jwt令牌，判断jwt是否为空或空串
        String jwt=httpServletRequest.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回未登录信息");
            Result result=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(result);
            httpServletResponse.getWriter().write(notLogin);
            return;
        }
        //4.jwt存在，校验jwt令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析jwt失败，返回未登录信息");
            Result result=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(result);
            httpServletResponse.getWriter().write(notLogin);
            return;
        }


        //放行
        log.info("解析jwt成功");
        filterChain.doFilter(servletRequest,servletResponse);


    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("filter过滤后");
    }
}
